<template>
  <el-dialog
    class="public-dialog"
    title="导入"
    width="720"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <VForm
        ref="formRef"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
      >
        <template #currency="{ value, input }">
          <CurrencySelect @update:model-value="input" :model-value="value" />
        </template>
        <template #excel="{ input, value }">
          <Upload
            label="Excel文件"
            require
            :modelValue="value"
            @update:modelValue="input"
            ref="uploadRef"
          >
            <template #headRight>
              <el-button
                text
                type="primary"
                @click.stop="handleDownLoadTemplate"
              >
                <span>下载模板</span>
              </el-button>
            </template>
          </Upload>
        </template>
        <template #original_bill="{ input, value }">
          <Upload
            label="原始账单文件"
            require
            :modelValue="value"
            @update:modelValue="input"
          >
            <template #headRight>
              <div class="text-[12px] text-[#999] leading-[17px]">
                <span class="mr-[2px] iconfont icon-hint_line"></span>
                <span>只是用来存储文件</span>
              </div>
            </template>
          </Upload>
        </template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import CurrencySelect from '@/components/CurrencySelect/index.vue'
import Upload from '@/components/Upload/index.vue'

import { getImportUrl } from '@/api/public'
import { tailBillImport, otherFeeImport } from '../../api'
import { watch } from 'vue'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  type: { type: String, default: 'order' },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  labelPosition: 'top',
  inline: true,
}

const rules = {
  bill_name: [{ required: true, message: '请输入账单名称', trigger: 'blur' }],
  logistics_id: [{ required: true, message: '请选择物流商', trigger: 'blur' }],
  currency: [{ required: true, message: '请选择费用', trigger: 'blur' }],
  is_cabinet: [{ required: true, message: '请选择导入方式', trigger: 'blur' }],
  rate: [{ required: true, message: '请输入费用', trigger: 'blur' }],
  file: [{ required: true, message: '请上传Excel文件', trigger: 'blur' }],
  original_bill: [
    { required: true, message: '请上传原始账单文件', trigger: 'blur' },
  ],
}

const formRef = ref()
const model = ref({ import_type: 'order' })
const loading = ref()
const orderData = ref()

const fieldList = [
  {
    field: 'import_type',
    label: '导入方式',
    type: 'radio',
    options: {
      data: [
        { label: '订单费用', value: 'order' },
        { label: '其他费用', value: 'other' },
      ],
    },
  },
  { type: 'br' },
  { field: 'file', slot: 'excel', full: true, style: { width: '100%' } },
]

watch(
  () => props.type,
  val => {
    model.value = Object.assign({ ...model.value }, { import_type: val })
  }
)

const handleDownLoadTemplate = async () => {
  const _type = {
    order: 'finance.tailBills',
    other: 'finance.tailOtherFee',
  }
  const { import_type } = await formRef.value.getFormValues()

  console.warn(import_type)
  const { data } = (await getImportUrl({ type: _type[import_type] })) || {}
  const _url = data?.uri
  if (_url) window.open(_url, 'noopener', 'noreferrer')
}

const isEdit = computed(() => {
  return !!props.id
})

const uploadRef = ref()
const handleSave = async () => {
  try {
    const formInfo = await formRef.value.submit()

    const { file } = formInfo
    const { id } = props

    console.warn(formInfo)
    const _prams = {
      file: file?.[0],
    }
    const _api = {
      order: tailBillImport,
      other: otherFeeImport,
    }

    const reqParams = _prams
    const { import_type } = await formRef.value.getFormValues()

    const { code, message } = await _api[import_type](reqParams)
    if (code !== 200) {
      ElMessage.warning(message)
      uploadRef.value.clearFiles()
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  await nextTick()
  formRef.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
